<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Services\OrderService;
use App\Services\ProductService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProductController extends Controller
{
    protected $ProductService;
    public function __construct(ProductService $ProductService)
    {
        $this->ProductService = $ProductService;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $title = $request->title;
        $pageSize = $request->pageSize ?: 10;
        $page = $request->page ?: 1;
        $skip = $page * $pageSize - $pageSize;

        $sql = $this->ProductService->get($title);
        $total = $sql->count();
        $data = $sql->skip($skip)->take($pageSize)->orderBy('created_at','desc')->get();
        return response()->json(['code' => 200, 'message' => '操作成功','page'=>$page,'pageSize'=>$pageSize,'total'=>$total,'data'=>$data]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show(Request $request)
    {
        $data = Product::find($request->id);
        //判断是否已经购买
        $data->isPay = false;
        if (Auth::guard('api')->check()) {
            $order = new OrderService();
            $user = Auth::guard('api')->user();
            $isPay = $order->isPay($user->id,$request->id,'product');
            $data->isPay = $isPay;
        }
        return response()->json(['code' => 200, 'message' => '操作成功','data'=>$data]);
    }

}
